package model

import (
	"errors"
	Mysql "gin/database"
	"gin/response"
	"gorm.io/gorm"
	"strings"
)

// 创建单条
func Insert(dst interface{}) (err error) {
	result := Mysql.DB.Create(dst)
	if result.Error != nil {
		return result.Error
	}
	return nil
}

// 查询单条
func Find(dst interface{}, filter map[string]interface{}, preloads []string) error {
	db := Mysql.DB.Model(dst)
	// 组装过滤条件
	if filter != nil {
		for key, val := range filter {
			vals := val.(map[string]interface{})
			if strings.Contains(key, "bw_") {
				db = db.Where(vals["condition"], vals["val1"], vals["val2"])
			} else {
				db = db.Where(vals["condition"], vals["val"])
			}
		}
	}
	if len(preloads) > 0 {
		for _, preload := range preloads {
			db = db.Preload(preload)
		}
	}

	result := db.Take(dst)
	if result.Error != nil {
		return result.Error
	}
	return nil

}

//查询多行
func Select(dst interface{}, result *response.SelectResp, filter map[string]interface{}, limit int, offset int, fields string, order string, preloads []string) (err error) {

	db := Mysql.DB.Model(dst)

	//rows = make([]Media,0)
	// 组装过滤条件
	if filter != nil {
		for key, val := range filter {
			vals := val.(map[string]interface{})
			if strings.Contains(key, "bw_") {
				db = db.Where(vals["condition"], vals["val1"], vals["val2"])
			} else {
				db = db.Where(vals["condition"], vals["val"])
			}
		}
	}
	// 获取总条数
	db.Count(&result.Total)

	if fields != "" {
		db = db.Select(fields)
	}

	if limit > 0 {
		db = db.Limit(limit)
	}
	if offset > 0 {
		db = db.Offset(offset)
	}

	// 应用排序参数
	if order != "" {
		db = db.Order(order)
	}

	// 预加载
	if len(preloads) > 0 {
		for _, preload := range preloads {
			db = db.Preload(preload)
		}
	}

	var queryResult *gorm.DB
	if filter != nil {
		queryResult = db.Find(result.Rows)

	} else {
		queryResult = db.Find(result.Rows)

	}

	//resultRows := result.Rows
	if queryResult.Error != nil {
		err = queryResult.Error
		return
	}

	return err
}

// 删除记录
func Delete(dst interface{}, filter map[string]interface{}) (int64, error) {

	db := Mysql.DB.Model(dst)

	// 组装过滤条件
	if filter == nil || len(filter) == 0 {
		return 0, errors.New("can`t delete records without filter")
	}

	for key, val := range filter {
		vals := val.(map[string]interface{})
		if strings.Contains(key, "bw_") {
			db = db.Where(vals["condition"], vals["val1"], vals["val2"])
		} else {
			db = db.Where(vals["condition"], vals["val"])
		}
	}

	result := db.Delete(dst)
	if result.Error != nil {
		return 0, result.Error
	}
	return result.RowsAffected, nil
}

// 通过id查找记录
func FindById(dst interface{}, id uint64, preloads []string) (err error) {

	db := Mysql.DB

	db = db.Model(dst).Where("id = ?", id)

	// 应用分页
	db = db.Select("*")

	if len(preloads) > 0 {
		for _, preload := range preloads {
			db = db.Preload(preload)
		}
	}

	result := db.First(dst)

	if result.Error != nil {
		err = result.Error
		return err
	}

	return nil
}

// 更新dict
func Update(dst interface{}, filter map[string]interface{}, updateFields map[string]interface{}) (int64, error) {
	db := Mysql.DB

	// 组装过滤条件
	if filter == nil || len(filter) == 0 {
		return 0, errors.New("can`t update records without filter")
	}

	for key, val := range filter {
		vals := val.(map[string]interface{})
		if strings.Contains(key, "bw_") {
			db = db.Where(vals["condition"], vals["val1"], vals["val2"])
		} else {
			db = db.Where(vals["condition"], vals["val"])
		}
	}

	result := db.Model(dst).Updates(&updateFields)
	if result.Error != nil {
		return 0, result.Error
	}
	return result.RowsAffected, nil
}

// 批量插入
func InsertAll(dst interface{}, records interface{}) (int64, error) {
	result := Mysql.DB.Model(dst).Create(records)
	if result.Error != nil {
		return 0, result.Error
	}
	return result.RowsAffected, nil
}
